// base64 转 文件
import Axios from 'axios';
import { message } from 'ant-design-vue';

// 上传图片
interface OssConfig {
  accessId: string;
  policy: string;
  signature: string;
  dir: string;
  host: string;
}

const uploadFile = async (oss: OssConfig, file: File): Promise<string | undefined> => {
  try {
    console.log(oss, "oss");
    console.log(file, "file");
    const { accessId, policy, signature, dir, host } = oss;
    const formData = new FormData();
    formData.append('OSSAccessKeyId', accessId);
    formData.append('policy', policy);
    formData.append('signature', signature);

    formData.append('key', dir);
    formData.append('success_action_status', '200');

    formData.append('file', file);

    const res = await Axios.request({
      url: host,
      method: 'POST',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    console.log(res, "res");
    
    if (res.status === 200) {
      console.log(`${host}/${dir}`, "上传OSS之后返回的地址");
      return `${host}/${dir}`;
    }
  } catch (err) {
    message.error("图片上传失败");
  }
};

// 对外暴露函数
export const OssUpload = async (oss: OssConfig, file: File): Promise<string | undefined> => {
  return await uploadFile(oss, file);
};
